package com.br3akr.rollerServer.engine;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Observable;
import java.util.Set;
import java.util.Stack;

public class Room extends Observable {
	private String message;
	private Set<Session> sessions;
	private Stack<Integer> availId;
	private Map<String, Integer> usedId;
	private FileWriter chatLog;
	private BufferedWriter out;
	
	public Room() {
		sessions = new HashSet<Session>();
		availId = new Stack<Integer>();
		usedId = new HashMap<String, Integer>();
		try {
			File file = new File("C:\\temp\\Chatlog-" + new Date().getTime() + ".log");
			if (!file.exists()) {
			}
			chatLog = new FileWriter(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		out = new BufferedWriter(chatLog);
		for (int i = 1; i < 9; i++) {
			availId.push(i);
		}
	}
	
	public String getMessage() {
		return message;
	}
	
	public Set<Session> getSessions() {
		return sessions;
	}
	
	public void setMessage(String message) {
		this.message = message;
		try {
			out.write("\n" + message);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		setChanged();
		notifyObservers();
	}
	
	public void updateAll() {
		setChanged();
		notifyObservers();
	}
	
	public void addSession(Session session) {
		int userId = 0;
		if (!availId.isEmpty()) {
			userId = availId.pop();
		}
		usedId.put(session.getPlayer(), userId);
		session.setUserId(userId);
		sessions.add(session);
		setChanged();
		notifyObservers();
	}
	
	public void removePlayer(String player) {
		Session issue = null;
		for (Session s : sessions) {
			if (s.getPlayer().equals(player)) {
				issue = s;
			}
		}
		sessions.remove(issue);
		int i = usedId.get(issue.getPlayer());
		if (i > 0) {
			availId.push(i);
		}
		usedId.remove(issue.getPlayer());
		setChanged();
		notifyObservers();
	}
}